# crud/sys_field_mapping.py
from sqlalchemy.orm import Session
from src.models.sys_field_mapping import SysFieldMapping
from src.schemas.sys_field_mapping import SysFieldMappingCreate, SysFieldMappingUpdate


def create_field_mapping(db: Session, field_mapping: SysFieldMappingCreate):
    """
    创建字段匹配记录。
    """
    db_field_mapping = SysFieldMapping(**field_mapping.dict())
    db.add(db_field_mapping)
    db.commit()
    db.refresh(db_field_mapping)
    return db_field_mapping


def create_field_mappings(db: Session, field_mappings: list[SysFieldMappingCreate]):
    """
    批量创建字段匹配记录。
    """
    db_field_mappings = [SysFieldMapping(**fm.dict()) for fm in field_mappings]
    try:
        db.add_all(db_field_mappings)
        db.commit()
        for db_field_mapping in db_field_mappings:
            db.refresh(db_field_mapping)
        return db_field_mappings
    except Exception as e:
        db.rollback()
        raise e


def get_field_mapping(db: Session, mapping_id: str):
    """
    根据 ID 获取字段匹配记录。
    """
    return db.query(SysFieldMapping).filter(SysFieldMapping.id == mapping_id).first()


def get_field_mappings(db: Session, skip: int = 0, limit: int = 100):
    """
    获取字段匹配记录列表。
    """
    return db.query(SysFieldMapping).offset(skip).limit(limit).all()


def update_field_mapping(db: Session, mapping_id: str, field_mapping: SysFieldMappingUpdate):
    """
    更新字段匹配记录。
    """
    db_field_mapping = db.query(SysFieldMapping).filter(SysFieldMapping.id == mapping_id).first()
    if db_field_mapping is None:
        return None
    update_data = field_mapping.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_field_mapping, key, value)
    db.commit()
    db.refresh(db_field_mapping)
    return db_field_mapping


def delete_field_mapping(db: Session, mapping_id: str):
    """
    删除字段匹配记录。
    """
    db_field_mapping = db.query(SysFieldMapping).filter(SysFieldMapping.id == mapping_id).first()
    if db_field_mapping is None:
        return None
    db.delete(db_field_mapping)
    db.commit()
    return db_field_mapping
